package control

import (
	"WeChatMGRA/server/conf"
	"gitee.com/yutiandou/wdtools/wdevent"
	"github.com/gin-gonic/gin"
	"sync/atomic"
)

type ginConfig struct {
	stat bool
	maxConnects int32
	nowConnects int32
}
var sconfig *ginConfig

//Gin_Config_Init gin框架自定义配置初始化
func Gin_Config_Init(conf * conf.Config){
	sconfig = &ginConfig{
		stat:true,
		maxConnects:conf.GinMaxConnects,
		nowConnects:0,
	}
	wdevent.AddEvent("gameover",func(interface{}){
		sconfig.stat = false
	})
}

//Gin_Global_Middle_Init ..全局中间件初始化
func Gin_Global_Middle_Init(server * gin.Engine){
	server.Use(Traffic_Control)
}

//Traffic_Control ..流量控制中间件
func Traffic_Control(g * gin.Context){
	if !sconfig.stat{
		g.Abort()
		return
	}
	if atomic.LoadInt32(&(sconfig.nowConnects))>sconfig.maxConnects{
		g.Abort()
		g.JSON(403,"请求超限")
	}
	atomic.AddInt32(&(sconfig.nowConnects),1)
	g.Next()
	atomic.AddInt32(&(sconfig.nowConnects),-1)
}
